package com.xiaoc.bulldozer.common.service.impl;

import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import javax.annotation.Resource;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.MapUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import com.xc.framework.common.job.OneMinuteJobService;
import com.xiaoc.bulldozer.common.dao.CommonConfigMapper;
import com.xiaoc.bulldozer.common.model.CommonConfig;
import com.xiaoc.bulldozer.common.service.CommonConfigService;
import com.xiaoc.bulldozer.common.service.cache.CommonConfigCacheService;

/**
 * CommonConfig Service 实现类
 * 
 * @author CodeGenerator
 * 
 * @date 2014-11-27 14:05:44
 * 
 */
@Service("commonConfigService")
public class CommonConfigServiceImpl implements CommonConfigService, CommonConfigCacheService, OneMinuteJobService {

    /**
     * 开关打开配置
     */
    private static final String SWITCH_ON = "on";

    /**
     * 系统配置信息，一分钟加载一次到内存
     */
    private Map<String, String> commonConfigCacheMap = new HashMap<String, String>();

    @Resource
    private CommonConfigMapper commonConfigMapper;

    @Override
    public String getValue(String configKey) {

        if (MapUtils.isEmpty(commonConfigCacheMap)) {
            refreshCacheData();
        }

        return commonConfigCacheMap.get(configKey);
    }

    @Override
    public String getValue(String configKey, String defaultValue) {
        String value = getValue(configKey);
        if(StringUtils.isNotBlank(value)){
            return value;
        }

        return defaultValue;
    }

    @Override
    public Set<String> getValueSet(String configKey) {

        if (MapUtils.isEmpty(commonConfigCacheMap)) {
            refreshCacheData();
        }

        String value = commonConfigCacheMap.get(configKey);

        if (StringUtils.isEmpty(value)) {
            return Collections.emptySet();
        }

        Set<String> valueSet = new HashSet<String>();
        String[] arry = StringUtils.split(value, ",");
        for (String s : arry) {
            valueSet.add(s);
        }

        return valueSet;
    }

    @Override
    public boolean contains(String configKey, String targetValue) {

        if (StringUtils.isEmpty(targetValue)) {
            return false;
        }

        if (MapUtils.isEmpty(commonConfigCacheMap)) {
            refreshCacheData();
        }

        String configValue = commonConfigCacheMap.get(configKey);
        if (StringUtils.isEmpty(configValue)) {
            return false;
        }

        String[] valueArry = StringUtils.split(configValue, ",");
        for (String value : valueArry) {
            if (value.equals(targetValue)) {
                return true;
            }
        }

        return false;
    }

    @Override
    public boolean switchON(String configKey) {
        String switchValue = getValue(configKey);
        if (switchValue != null && SWITCH_ON.equalsIgnoreCase(switchValue)) {
            // 开关打开
            return true;
        }

        return false;
    }

    @Override
    public void refreshCacheData() {

        Map<String, String> commonConfigMap = new HashMap<String, String>();

        List<CommonConfig> commonConfigList = commonConfigMapper.getAllCommonConfigList();

        if (CollectionUtils.isEmpty(commonConfigList)) {
            return;
        }

        for (CommonConfig commonConfig : commonConfigList) {
            commonConfigMap.put(commonConfig.getConfigKey(), commonConfig.getConfigValue());
        }

        commonConfigCacheMap = commonConfigMap;
    }

    @Override
    public String getConfigValueFromDB(String configKey) {
        CommonConfig existCommonConfig = commonConfigMapper.getCommonConfigByConfigKey(configKey);
        return existCommonConfig == null ? null : existCommonConfig.getConfigValue();
    }

    @Override
    public CommonConfig getCommonConfigFromDb(String configKey) {
        return commonConfigMapper.getCommonConfigByConfigKey(configKey);
    }

    @Override
    public List<CommonConfig> getAllCommonConfigList() {
        return commonConfigMapper.getAllCommonConfigList();
    }

    @Override
    public void save(CommonConfig commonConfig) {

        CommonConfig existCommonConfig = commonConfigMapper.getCommonConfigByConfigKey(commonConfig.getConfigKey());

        if (existCommonConfig != null) {
            throw new RuntimeException("配置项[" + commonConfig.getConfigKey() + "]已存在");
        }

        commonConfig.setConfigValue(trimSpecialCharacter(commonConfig.getConfigValue()));
        commonConfig.setUpdateTime(System.currentTimeMillis());
        commonConfigMapper.save(commonConfig);
    }

    @Override
    public void update(CommonConfig commonConfig) {

        CommonConfig existCommonConfig = commonConfigMapper.getCommonConfigByConfigKey(commonConfig.getConfigKey());

        if (existCommonConfig == null) {
            throw new RuntimeException("配置项[" + commonConfig.getConfigKey() + "]不存在");
        }

        existCommonConfig.setConfigValue(trimSpecialCharacter(commonConfig.getConfigValue()));
        existCommonConfig.setRemark(commonConfig.getRemark());
        existCommonConfig.setUpdateTime(System.currentTimeMillis());
        existCommonConfig.setUpdateUser(commonConfig.getUpdateUser());

        commonConfigMapper.update(existCommonConfig);
    }

    private String trimSpecialCharacter(String input) {
        return input == null ? null : input.replaceAll("[ \r\n]", "");
    }

    @Override
    public void updateConfigValue(String configKey, String configValue) {

        if (StringUtils.isEmpty(configKey)) {
            return;
        }

        CommonConfig existCommonConfig = commonConfigMapper.getCommonConfigByConfigKey(configKey);
        if (existCommonConfig == null || existCommonConfig.getConfigValue().equals(configValue)) {

            return;
        }

        existCommonConfig.setConfigValue(configValue);
        existCommonConfig.setUpdateTime(System.currentTimeMillis());

        commonConfigMapper.update(existCommonConfig);

        commonConfigCacheMap.put(configKey, configValue);

    }

}
